﻿using Modbus.Messages;

namespace Modbus
{
	partial class ModbusClient
	{
		public void WriteSingleCoil(byte slaveAddress, int outputAddress, bool outputValue)
		{
			//
			// Input arguments validation.
			//

			Ensure.ArgumentInRange(SR.Argument_outputAddress, outputAddress, MinDataAddress, MaxDataAddress);

			//
			// Internal state validation.
			//

			this.ThrowIfDisposed();

			//
			// Request creation.
			//

			WriteSingleCoilMessage request = new WriteSingleCoilMessage();

			request.FunctionCode = FunctionCodes.WriteSingleCoil;
			request.OutputAddress = (ushort)(outputAddress);
			request.OutputValue = (outputValue ? (ModbusSpecification.OutputStateON)
			                                   : (ModbusSpecification.OutputStateOFF));

			//
			// Perform transaction.
			//

			if (slaveAddress == BroadcastAddress)
			{
				this.transport.Request(slaveAddress, request);
			}
			else
			{
				var response = this.transport.Request<WriteSingleCoilMessage>(slaveAddress, request);

				//
				// Response validation.
				//

				if (response.OutputAddress != request.OutputAddress)
				{
					throw new MismatchResponseException(SR.ModbusMessageField_OutputAddress);
				}
				if (response.OutputValue != request.OutputValue)
				{
					throw new MismatchResponseException(SR.ModbusMessageField_OutputValue);
				}
			}
		}
	}
}
